package com.zxq.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 灰度控制工具类
 */
public class GrayUtil {

    public static final String COMMA = ",";

    /**
     * 按网格站进行匹配
     *
     * @param strategy MCC中配置的策略，配置仓ID，多个英文逗号隔开，"0"或者空不匹配
     * @param poiId    网格站ID
     * @return
     */
    public static boolean matchByPoi(String strategy, long poiId) {
        if (StringUtils.isBlank(strategy) || "0".equals(strategy) || poiId == 0L) {
            return false;
        }
        return Arrays.stream(strategy.split(COMMA))
                .mapToLong(NumberUtils::toLong)
                .anyMatch(id -> id == poiId);
    }

    /**
     * 按百分比进行匹配（按分表总数计算）
     *
     * @param percent MCC中配置的百分比，0-100
     * @param poiId   网格站ID
     * @return
     */
    public static boolean matchByPercent(int percent, long poiId) {
        if (percent > 0 && percent <= 100) {
            if (percent == 100) {
                // 100 默认全量，无需计算
                return true;
            }
            //分表总数
            int tableSum = 200;
            int mod = (int) (poiId % tableSum);
            if (mod <= (percent * 2)) {
                //命中
                return true;
            }
        }
        return false;
    }


    /**
     * 百分比和网格站灰度兼容
     *
     * @param strategy 策略   {"allFlag":false,"whitePoiIds":[],"percent":0}
     * @param poiId    网格站ID
     * @return boolean
     * @see GrayConfigSwitch
     */
    public static boolean matchGray(String strategy, long poiId) {
        try {
            GrayConfigSwitch grayConfigSwitch = JsonUtil.toObject(strategy, GrayConfigSwitch.class);
            if (grayConfigSwitch.isAllFlag() || grayConfigSwitch.getWhitePoiIds().contains(poiId) || matchByPercent(grayConfigSwitch.getPercent(), poiId)) {
                return true;
            }
            return false;
        } catch (Exception e) {
            System.out.println(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

}


class GrayConfigSwitch {

    //是否全量开启
    private boolean allFlag;

    private List<Long> whitePoiIds;

    //百分比
    private int percent;

    public boolean isAllFlag() {
        return allFlag;
    }

    public void setAllFlag(boolean allFlag) {
        this.allFlag = allFlag;
    }

    public List<Long> getWhitePoiIds() {
        return whitePoiIds;
    }

    public void setWhitePoiIds(List<Long> whitePoiIds) {
        this.whitePoiIds = whitePoiIds;
    }

    public int getPercent() {
        return percent;
    }

    public void setPercent(int percent) {
        this.percent = percent;
    }
}
